'use client';

import type { IPostEditInfo, IPostNewInfo } from '@/interfaces';
import { type ChangeEvent, useContext } from 'react';
import { PostEditContext } from '@/contexts/post-edit';
import { isValidLink } from '@/lib/tool';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { updatePostEditInfo } from '@/services/api';

export type TContentTypeTranslatedField =
  | 'update'
  | 'default'
  | 'link'
  | 'none'
  | 'contentLinkPlaceholder'
  | 'contentTypePlaceholder'
  | 'nonePlaceholder'
  | 'updateCompleted';

export default function ContentType({
  source,
  translatedFields = {
    update: '更新',
    default: '默认',
    link: '链接',
    none: '无内容',
    contentTypePlaceholder: '请选择内容类型',
    contentLinkPlaceholder: '请输入内容链接',
    nonePlaceholder: '手动清空编辑器中的内容后生效',
    updateCompleted: '更新完成',
  },
}: {
  source: IPostEditInfo | IPostNewInfo;
  translatedFields?: Record<TContentTypeTranslatedField, any>;
}) {
  const context = useContext(PostEditContext);
  const isEdit = 'basic' in source;
  const { form, setForm } = context;
  const { show } = useToast();

  const updatePostEditInfoMutation = useMutation(updatePostEditInfo);

  async function onClickUpdate() {
    if (!isEdit) {
      show({
        type: 'SUCCESS',
        message: translatedFields.updateCompleted,
      });
      return;
    }

    try {
      const _form: any = {
        contentType: form.contentType,
        contentLink: form.contentLink,
        name: form.name,
        content: form.content,
      };

      if (
        _form.contentType === 'LINK' &&
        _form.contentLink &&
        isValidLink(_form.contentLink)
      ) {
        _form.content = `<a href="${_form.contentLink}" rel="noopener noreferrer" target="_blank">${_form.contentLink}</a>`;
      } else if (_form.content) {
        _form.contentType = 'DEFAULT';
      } else {
        _form.content = _form.name;
        _form.contentType = 'NONE';
      }

      await updatePostEditInfoMutation.mutateAsync({
        id: source.basic.id,
        data: _form,
      });
    } catch (e) {
      updatePostEditInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChange(e: ChangeEvent<HTMLSelectElement | HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <div className="card border-0">
      <div className="card-body d-flex flex-column gap-4 my-4">
        <select
          name="contentType"
          value={form.contentType}
          onChange={onChange}
          className="form-select"
          placeholder={translatedFields.contentTypePlaceholder}
        >
          <option value="DEFAULT">{translatedFields.default}</option>
          <option value="LINK">{translatedFields.link}</option>
          <option value="NONE">{translatedFields.none}</option>
        </select>

        {form.contentType === 'LINK' && (
          <input
            type="text"
            name="contentLink"
            value={form.contentLink}
            className="form-control"
            placeholder={translatedFields.contentLinkPlaceholder}
            onChange={onChange}
          />
        )}

        {form.contentType === 'NONE' && !isEdit && (
          <div className="form-text">
            <i className="bi bi-info-circle me-2"></i>
            {translatedFields.nonePlaceholder}
          </div>
        )}

        <div className="d-grid col-2">
          <button
            onClick={onClickUpdate}
            type="button"
            className="btn btn-success"
          >
            {translatedFields.update}
          </button>
        </div>
      </div>
    </div>
  );
}
